package com.cloudkinto.service.invoice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.MathUtils;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.extentity.InvoiceRecordDto;
import com.cloudkinto.extentity.InvoiceReviewDto;
import com.cloudkinto.service.company.CompanyService;
import com.cloudkinto.service.dic.DicBusinessItemService;
import com.cloudkinto.service.file.FileMoreService;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.file.vo.FileRes;
import com.cloudkinto.service.finance.RechargeRecordService;
import com.cloudkinto.service.finance.vo.RechargeRecordMatchInvoiceReq;
import com.cloudkinto.service.invoice.InvoiceRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.invoice.InvoiceTitleService;
import com.cloudkinto.service.invoice.vo.*;
import com.cloudkinto.service.message.MessageNoticeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author hjy
 * @since 2021-07-13
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class InvoiceRecordServiceImpl extends ServiceImpl<InvoiceRecordDao, InvoiceRecordDo> implements InvoiceRecordService {
    @Autowired
    private InvoiceRecordDao dao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private InvoiceTitleService invoiceTitleService;
    @Autowired
    private InvoiceTitleDao invoiceTitleDao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private DicBusinessItemService dicBusinessItemService;
    @Autowired
    private FileService fileService;
    @Autowired
    private FileMoreService fileMoreService;
    @Autowired
    private RechargeRecordService rechargeRecordService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private MailDao mailDao;
    @Autowired
    private RechargeTypeDao rechargeTypeDao;
    @Autowired
    private MessageNoticeService messageNoticeService;

    //临时存储路径
    @Value("${gbc.uploadPath.filePathTemp}")
    private String filePathTemp;

    @Override
    public SingleResult addInit(Long companyId) {
        Map map = new HashMap();
        //计算出可以开票得金额
        double allAmount = dao.getSumCostRecord(companyId);
        double hadInvoiceAmount = dao.getSumHadInvoiceAmount(companyId);
        map.put("leftAmount", MathUtils.numberFormat(MathUtils.sub(allAmount, hadInvoiceAmount)));

        //查询可以选择得发票抬头
        List<Map> invoiceList = invoiceTitleService.selectInvoiceListInit(companyId, null);
        map.put("invoiceTitleList", invoiceList);

        //查询上次开票使用的开票抬头
        CompanyDo companyDo = companyDao.selectById(companyId);
        if (companyDo != null && companyDo.getLastInvoiceTitleId() != null && companyDo.getLastInvoiceTitleId() != 0) {
            InvoiceTitleDo lastInvoiceTitle = invoiceTitleDao.selectById(companyDo.getLastInvoiceTitleId());
            map.put("lastInvoiceTitle", lastInvoiceTitle);
            map.put("lastInvoiceType", companyDo.getLastInvoiceType());
        }
        return SingleResult.success(map);
    }

    @Override
    public InvoiceRecordAddReq add(InvoiceRecordAddReq req, Long userId) {
        if (req.getCompanyId() == null) {
            throw new BizException(SysConstant.Pls_Choose_Company);
        }
        if (req.getInvoiceTitleId() == null || req.getInvoiceTitleId() == 0) {
            throw new BizException(SysConstant.InvoiceRecord_Choose_Title);
        }
        InvoiceTitleDo et = invoiceTitleDao.selectById(req.getInvoiceTitleId());
        if (et == null) {
            throw new BizException(SysConstant.InvoiceRecord_Title_Expired);
        }

        RechargeRecordDo rechargeRecordDo = rechargeRecordService.getById(req.getRechargeRecordId());
        if (rechargeRecordDo == null) {
            //先开票后充值的情况
//            Map<String, String> map = new HashMap<>();
//            map.put("id", req.getInvoiceTitleId()+"");
//            map.put("companyId", req.getCompanyId()+"");
//            List<InvoiceTitleOweDetailRes> list = invoiceTitleService.oweList(map);
//            if (list.size() > 2 && list.get(0).getOweAmount() > 0) {
//                throw new BizException(SysConstant.InvoiceRecord_AddCheck_Error);
//            }
            int unMatchInvoiceRecordCount = getUnMatchInvoiceRecordCount(req.getCompanyId(), et.getTaxNumber());
            if (unMatchInvoiceRecordCount > 2) {
                throw new BizException(SysConstant.InvoiceRecord_AddCheck_Error);
            }
        }
        InvoiceRecordDo entityDo = new InvoiceRecordDo();
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setBank(et.getBank());
        entityDo.setBankAccount(et.getBankAccount());
        entityDo.setCompanyAddress(et.getCompanyAddress());
        entityDo.setCompanyTelephone(et.getCompanyTelephone());
        entityDo.setInvoiceTitle(et.getInvoiceTitle());
        entityDo.setTaxNumber(et.getTaxNumber());
        handlerAddBefore(entityDo, userId);
        if (entityDo.getStatus() == null || entityDo.getStatus() == 0L) {
            entityDo.setStatus(DicBusinessItemConstant.invoiceApplyStatus);
        }
        dao.insert(entityDo);
        if (rechargeRecordDo != null) {
            rechargeRecordDo.setInvoiceRecordId(entityDo.getId());
            rechargeRecordService.updateById(rechargeRecordDo);
        }
        //开票成功后，将开票抬头id 保存到t_company表中
        updateCompanyMsg(req.getInvoiceTitleId(), req.getType(), req.getCompanyId());
        return req;
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(InvoiceRecordDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(InvoiceRecordDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id, Long companyId) {
        InvoiceRecordDo et = dao.selectById(id);
        if (et == null) {
            throw new BizException(SysConstant.Error_Data_HadDelete);
        }
        Map map = new HashMap();
        //计算出可以开票得金额
        double allAmount = dao.getSumCostRecord(et.getCompanyId());
        double hadInvoiceAmount = dao.getSumHadInvoiceAmount(et.getCompanyId());
        map.put("leftAmount", MathUtils.sub(allAmount, MathUtils.add(hadInvoiceAmount, et.getInvoiceAmount())));

        //查询可以选择得发票抬头
//        Map map1 = new HashMap();
//        if (companyId != null)
//            map1.put("companyId", companyId + "");
        List<Map> invoiceList = invoiceTitleService.selectInvoiceListInit(et.getCompanyId(), et.getTaxNumber());
        map.put("invoiceTitleList", invoiceList);
        InvoiceRecordDetailRes req = new InvoiceRecordDetailRes();

        //判断下开票得状态
        if (!et.getStatus().equals(DicBusinessItemConstant.invoiceApplyStatus)) {
            String msg = DicBusinessItemConstant.invoicePassStatus.equals(et.getStatus()) ? "开票成功" : (DicBusinessItemConstant.invoiceNotPassStatus.equals(et.getStatus()) ? "驳回" : "");
            throw new BizException(SysConstant.InvoiceRecord_Update_Error, msg);
        }
        BeanUtils.copyProperties(et, req);
        this.handlerDetailAfter(req);
        map.put("InvoiceRecord", req);
        return SingleResult.success(map);
    }

    @Override
    public InvoiceRecordUpdateReq update(InvoiceRecordUpdateReq req, Long userId) {
        InvoiceRecordDo entityDo = dao.selectById(req.getId());
        if (entityDo == null) {
            throw new BizException(SysConstant.Error_Data_NotExist);
        }
        //判断下开票得状态
        if (!entityDo.getStatus().equals(DicBusinessItemConstant.invoiceApplyStatus)) {
//            String msg = DicBusinessItemConstant.invoicePassStatus.equals(entityDo.getStatus()) ? "审核通过" : (DicBusinessItemConstant.invoiceNotPassStatus.equals(entityDo.getStatus())
//                    ? "作废" : (DicBusinessItemConstant.invoiceSuccessStatus.equals(entityDo.getStatus()) ? "开票成功" : "审核通过"));
            String msg = DicBusinessItemConstant.invoicePassStatus.equals(entityDo.getStatus()) ? "开票成功" : (DicBusinessItemConstant.invoiceNotPassStatus.equals(entityDo.getStatus()) ? "驳回" : "");
            throw new BizException(SysConstant.InvoiceRecord_Update_Error, msg);
        }
        //更新时需要将本条开票记录 的开票金额另算
        if (!updateCheck(req.getCompanyId(), MathUtils.sub(req.getInvoiceAmount(), entityDo.getInvoiceAmount()))) {
            throw new BizException(SysConstant.InvoiceRecord_Balance_Error);
        }
        if (req.getInvoiceTitleId() != null && req.getInvoiceTitleId() != 0L) {
            InvoiceTitleDo et = invoiceTitleDao.selectById(req.getInvoiceTitleId());
            if (et == null) {
                throw new BizException(SysConstant.InvoiceRecord_Title_Expired);
            }

            //更新t_company表中的上次开票抬头id
            updateCompanyMsg(req.getInvoiceTitleId(), req.getType(), req.getCompanyId());
            //由titileId说明修改了该条开票信息的公司抬头，更新抬头信息
            entityDo.setBank(et.getBank());
            entityDo.setBankAccount(et.getBankAccount());
            entityDo.setCompanyAddress(et.getCompanyAddress());
            entityDo.setCompanyTelephone(et.getCompanyTelephone());
            entityDo.setInvoiceTitle(et.getInvoiceTitle());
            entityDo.setTaxNumber(et.getTaxNumber());
        }
        entityDo.setType(req.getType());
        entityDo.setInvoiceAmount(req.getInvoiceAmount());
        entityDo.setTips(req.getTips());
//        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);

        return req;
    }

    public void updateCompanyMsg(Long invoiceTitleId, Integer type, Long companyId) {
        //开票成功后，将开票抬头id 保存到t_company表中
        CompanyDo companyDo = new CompanyDo();
        companyDo.setId(companyId);
        companyDo.setLastInvoiceTitleId(invoiceTitleId);
        companyDo.setLastInvoiceType(type);
        companyDao.updateById(companyDo);
    }

    //编辑校验
    private boolean updateCheck(Long companyId, double invoiceAmount) {
        double allAmount = dao.getSumCostRecord(companyId);
        double hadInvoiceAmount = dao.getSumHadInvoiceAmount(companyId);
        if ((MathUtils.sub(allAmount, hadInvoiceAmount)) < invoiceAmount) {
            return false;
        }
        return true;
    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(InvoiceRecordDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(InvoiceRecordDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        InvoiceRecordDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(InvoiceRecordDo entityDo, Long userId) {
//        entityDo.setDeleteBy(userId);
//        entityDo.setDeleteTime(new Date());
    }

    @Override
    public InvoiceRecordDetailRes detail(Long id) {
        InvoiceRecordDo entityDo = dao.selectById(id);
        InvoiceRecordDetailRes req = new InvoiceRecordDetailRes();
        if (entityDo != null) {
            BeanUtils.copyProperties(entityDo, req);
        }
        handlerDetailAfter(req);
        return req;
    }


    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(InvoiceRecordDetailRes res) {
        CompanyDo companyDo = companyDao.selectById(res.getCompanyId());
        if (companyDo != null) {
            res.setCompanyName(companyDo.getName());
        }
        RechargeRecordDo rechargeRecordDo = rechargeRecordService.getOne(new LambdaQueryWrapper<RechargeRecordDo>().eq(RechargeRecordDo::getInvoiceRecordId, res.getId()).last("limit 1"));
        if (rechargeRecordDo != null) {
            res.setRechargeStatus(SysConstant.DELETE_FLAG_TRUE);
            res.setRechargeRecordId(rechargeRecordDo.getId());
            res.setRechargeAmount(rechargeRecordDo.getAmountRmb());
            res.setRechargeImage(fileService.getFilePath(rechargeRecordDo.getCertificateImageFileId()));
            if (rechargeRecordDo.getCurrency() == null) {
                RechargeTypeDo rechargeTypeDo = rechargeTypeDao.selectById(rechargeRecordDo.getRechargeTypeId());
                if (rechargeTypeDo != null) {
                    res.setCurrency("0".equals(rechargeTypeDo.getCurrency()) ? DicBusinessItemConstant.CurrencyTypeRmb : DicBusinessItemConstant.CurrencyTypeJpy);
                }
            } else {
                res.setCurrency(rechargeRecordDo.getCurrency());
            }
        } else {
            res.setRechargeStatus(SysConstant.DELETE_FLAG_FALSE);
        }
        res.setApplyTime(res.getCreateTime());
        return res;
    }

    @Override
    public SingleResult pageInit(Long companyId) {
        Map result = new HashMap();
        //查询开票状态
        result.put("invoiceStatusList", dicBusinessItemService.getDicItemList(DicBusinessConstant.invoiceStatus));

        Map map1 = new HashMap();
        map1.put("id", 0);
        map1.put("name", StringsUtil.createI18Message("固定月开"));
        Map map2 = new HashMap();
        map2.put("id", 1);
        map2.put("name", StringsUtil.createI18Message("一次开票"));
        List<Map> invoiceTypeList = Arrays.asList(map1, map2);
        result.put("invoiceTypeList", invoiceTypeList);
        if (companyId != null) {
            CompanyDo companyDo = companyDao.selectById(companyId);
            if (companyDo != null) {
                result.put("invoiceType", companyDo.getLastInvoiceType());
            }
        }
        //公司下拉框
        result.put("companyTree", companyService.getList().getData());
        return SingleResult.success(result);
    }

    @Override
    public List<InvoiceRecordDetailRes> getList(Map<String, String> map) {
        QueryWrapper<InvoiceRecordDo> wrapper = queryBuild(map);
        List<InvoiceRecordDo> list = this.list(wrapper);
        List<InvoiceRecordDetailRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
//        QueryWrapper<InvoiceRecordDo> wrapper = queryBuild(map);
        IPage<InvoiceRecordDto> page = pageInitDto(map);
//        page = this.page(page, wrapper);
        List<InvoiceRecordDto> recordDos = dao.listPageDto(page, map);
        List<InvoiceRecordDetailRes> resList = handlerListAfterDto(recordDos);
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<InvoiceRecordDetailRes> handlerListAfterDto(List<InvoiceRecordDto> list) {
        List<InvoiceRecordDetailRes> result = new ArrayList<>();
        for (InvoiceRecordDto et : list) {
            InvoiceRecordDetailRes req = new InvoiceRecordDetailRes();
            BeanUtils.copyProperties(et, req);
            CompanyDo companyDo = companyDao.selectById(et.getCompanyId());
            if (companyDo != null) {
                req.setCompanyCode(companyDo.getCompanyCode());
            }
            RechargeRecordDo rechargeRecordDo = rechargeRecordService.getOne(new LambdaQueryWrapper<RechargeRecordDo>()
                    .eq(RechargeRecordDo::getInvoiceRecordId, req.getId()).last("limit 1"));
            if (rechargeRecordDo != null) {
                req.setRechargeStatus(SysConstant.DELETE_FLAG_TRUE);
                req.setRechargeRecordId(rechargeRecordDo.getId());
                req.setRechargeAmount(rechargeRecordDo.getAmountRmb());
                req.setRechargeImage(fileService.getFilePath(rechargeRecordDo.getCertificateImageFileId()));
            } else {
                req.setRechargeStatus(SysConstant.DELETE_FLAG_FALSE);
            }
            result.add(req);
        }
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<InvoiceRecordDetailRes> handlerListAfter(List<InvoiceRecordDo> list) {
        List<InvoiceRecordDetailRes> result = new ArrayList<>();
        for (InvoiceRecordDo et : list) {
            InvoiceRecordDetailRes req = new InvoiceRecordDetailRes();
            BeanUtils.copyProperties(et, req);
            CompanyDo companyDo = companyDao.selectById(req.getCompanyId());
            if (companyDo != null) {
                req.setCompanyName(companyDo.getName());
            }
            result.add(req);
        }
        return result;
    }

    private IPage<InvoiceRecordDo> pageInit(Map<String, String> map) {
        IPage<InvoiceRecordDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private IPage<InvoiceRecordDto> pageInitDto(Map<String, String> map) {
        IPage<InvoiceRecordDto> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<InvoiceRecordDo> queryBuild(Map<String, String> map) {
        QueryWrapper<InvoiceRecordDo> wrapper = new QueryWrapper<>();
//        if (StringUtils.isNotBlank(map.get("keyword"))) {
//            wrapper.and(invoiceRecordDoQueryWrapper -> invoiceRecordDoQueryWrapper.like("invoice_title",map.get("keyword"))
//                    .or().like("bank", map.get("keyword")));
//        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.and(invoiceRecordDoQueryWrapper -> invoiceRecordDoQueryWrapper.eq("status", map.get("status")));
        }
        if (StringUtils.isNotBlank(map.get("type"))) {
            wrapper.and(invoiceRecordDoQueryWrapper -> invoiceRecordDoQueryWrapper.eq("`type`", map.get("type")));
        }
        return wrapper;
    }

    @Override
    public Map<String, Object> getInvoiceTitle(Long id) {
        InvoiceTitleDo invoiceTitleDo = invoiceTitleDao.selectById(id);
        Map<String, Object> msg = new HashMap<>();
        if (invoiceTitleDo != null) {
            msg.put("id", invoiceTitleDo.getId());
            msg.put("invoiceTitle", invoiceTitleDo.getInvoiceTitle());
            msg.put("taxNumber", invoiceTitleDo.getTaxNumber());
            msg.put("companyAddress", invoiceTitleDo.getCompanyAddress());
        }
        return msg;
    }


    /**
     * 暂停开票
     */
    @Override
    public String stop(Long companyId) {
        CompanyDo companyDo = companyDao.selectById(companyId);
        if (companyDo == null) {
            throw new BizException(SysConstant.Company_NotExist);
        }
        companyDo.setLastInvoiceType(1);
        companyDao.updateById(companyDo);
        return "修改成功";
    }


    /**
     * 开票
     */
    @Override
    public String review(InvoiceRecordReviewReq req) {
        InvoiceRecordDo et = dao.selectById(req.getId());
        et.setStatus(req.getStatus());
        et.setInvoiceImageFileId(req.getFileId());

        et.setInvoiceLink(fileService.getFilePath(req.getFileId()));
        if (DicBusinessItemConstant.invoiceNotPassStatus.equals(req.getStatus()) && StringUtils.isBlank(et.getInvoiceLink())) {
            throw new BizException(SysConstant.InvoiceRecord_Review_Error);
        }
        dao.updateById(et);
        return "操作成功";
    }

    @Override
    public Object check(InvoiceRecordCheckReq req, Long userId) {
        InvoiceRecordDo invoiceRecordDo = dao.selectById(req.getId());
        if (invoiceRecordDo == null) {
            throw new BizException(SysConstant.Error_Data_NotExist);
        }
        if (StringUtils.isNotBlank(req.getInvoiceNumber())) {
            invoiceRecordDo.setInvoiceNumber(req.getInvoiceNumber().trim());
        }
        if (req.getType() == 1) {
            invoiceRecordDo.setStatus(DicBusinessItemConstant.invoicePassStatus);
        } else {
            invoiceRecordDo.setStatus(DicBusinessItemConstant.invoiceNotPassStatus);
            //如果改发票已关联充值记录，删除关联id
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("invoice_record_id", invoiceRecordDo.getId());
            RechargeRecordDo rechargeRecordDo = rechargeRecordService.getOne(wrapper);
            if (rechargeRecordDo != null) {
                rechargeRecordDo.setInvoiceRecordId(null);
                rechargeRecordService.updateById(rechargeRecordDo);
            }
        }
        invoiceRecordDo.setUpdateBy(userId);
        invoiceRecordDo.setUpdateTime(new Date());
        invoiceRecordDo.setExpectedMonth(TimeUtils.getCurrentDateFormat());
        dao.updateById(invoiceRecordDo);
        threadPoolTaskExecutor.execute(() -> {
            //匹配发票连接
            this.matchInvoiceLink(req.getId());
        });
        return 1;
    }

    public void matchInvoiceLink(Long id) {
        InvoiceRecordDo invoiceRecordDo = dao.selectById(id);
        if (invoiceRecordDo == null) {
            return;
        }
        List<MailDo> list = mailDao.selectList(new LambdaQueryWrapper<MailDo>()
                .eq(MailDo::getFolderName, "发票邮件").eq(MailDo::getSubject, "增值税电子发票交付通知")
                .ge(MailDo::getSendDate, DateUtils.dateFormatToString(DateUtils.passingDate(new Date(), -20)))
                .last(" order by send_date desc"));
        for (MailDo mailDo : list) {
            if (mailDo.getTextPlain().contains("尊敬的客户：\r\n    您好！\r\n    您收到一张来自筋斗云物流（苏州）有限公司开具的电子发票，发票详情如下：\r\n    发票代码：") && mailDo.getTextPlain().contains("发票号码：" + invoiceRecordDo.getInvoiceNumber().trim())) {
                String str = "https://bswj.jiangsu.chinatax.gov.cn:7001/preview.html?code=";
                String str2 = "\r\n\r\n\r\n    OFD版式文件阅读器下载地址：";
                if (!mailDo.getTextPlain().contains(str) || !mailDo.getTextPlain().contains(str2)) {
                    continue;
                }
                String code = mailDo.getTextPlain().substring(mailDo.getTextPlain().indexOf(str) + str.length(), mailDo.getTextPlain().indexOf(str2));
                if (StringUtils.isBlank(code)) {
                    break;
                }
                String url = "https://bswj.jiangsu.chinatax.gov.cn:7001/api?action=getDoc&code=" + code + "&type=12";
                invoiceRecordDo.setInvoiceLink(url);
                invoiceRecordDo.setStatus(DicBusinessItemConstant.invoiceSuccessStatus);
                dao.updateById(invoiceRecordDo);
                //第一种 格式匹配成功
                return;
//                    File file = fileService.getFile(url, filePathTemp+ File.separator + code + ".pdf");
//                    InputStream inputStream = null;
//                    try {
//                        inputStream = new FileInputStream(file);
//                    } catch (FileNotFoundException e) {
//                        e.printStackTrace();
//                    }
//                    //上传到服务器
//                    Long fileId = fileService.uploadFileToFormalPath(inputStream, file.getName());
//                    if (fileId != null && fileId != 0) {
//                        invoiceRecordDo.setInvoiceLink(fileService.getFilePath(fileId));
//                                           dao.updateById(invoiceRecordDo);
//                    }
            }
        }

        boolean flag = this.matchSecond(invoiceRecordDo);
        if (flag) {
            return;
        }
        flag = this.matchThird(invoiceRecordDo);
        if (flag) {
            return;
        }
    }

    public boolean matchThird(InvoiceRecordDo invoiceRecordDo) {
        //第三种格式  发票号在主题上 如： 这是您发票号码为23322000000006709541的全电发票，请注意查收
        String subject3 = "这是您发票号码为"+invoiceRecordDo.getInvoiceNumber().trim()+"的全电发票，请注意查收";
        MailDo mailDo3 = mailDao.selectOne(new LambdaQueryWrapper<MailDo>().eq(MailDo::getSubject, subject3).last(" order by send_date desc limit 1"));
        if (mailDo3 == null) {
            return false;
        }
        List<FileRes> fileList = fileMoreService.getFileList(mailDo3.getId(), StaticDict.File_Type.Mail.getValue());
        if (fileList.size() == 0) {
            return false;
        }
        if (StringUtils.isBlank(fileList.get(0).getUrl())) {
            return false;
        }
        invoiceRecordDo.setInvoiceLink(fileList.get(0).getUrl());
        invoiceRecordDo.setStatus(DicBusinessItemConstant.invoiceSuccessStatus);
        dao.updateById(invoiceRecordDo);
        return true;
    }


    public boolean matchSecond(InvoiceRecordDo invoiceRecordDo) {
        //第二种格式
        //发票邮件格式更改 ：【电子发票】您收到一张新的电子发票[发票号码:03092732]
        String subject = "【电子发票】您收到一张新的电子发票[发票号码:" + invoiceRecordDo.getInvoiceNumber().trim() + "]";
        MailDo mailDo = mailDao.selectOne(new LambdaQueryWrapper<MailDo>().eq(MailDo::getSubject, subject).last(" order by send_date desc limit 1"));
        if (mailDo == null) {
            return false;
        }
        String str = "<div class=\"lan\">&nbsp;&nbsp;<a href=\"";
        String str2 = "\" style=\"color:#00479d;\"";
        String url = mailDo.getTextHtml().substring(mailDo.getTextHtml().indexOf(str) + str.length(), mailDo.getTextHtml().indexOf(str2));
        if (StringUtils.isNotBlank(url)) {
            invoiceRecordDo.setInvoiceLink(url);
            invoiceRecordDo.setStatus(DicBusinessItemConstant.invoiceSuccessStatus);
            dao.updateById(invoiceRecordDo);
            return true;
        }
        return false;
    }

    /**
     * 定时器 审核通过得 发票 每天去匹配发票连接
     *
     * @return
     */
    @Override
    public void timingMatchInvoiceLink() {
        List<InvoiceRecordDo> list = dao.selectList(new LambdaQueryWrapper<InvoiceRecordDo>()
                .eq(InvoiceRecordDo::getStatus, DicBusinessItemConstant.invoicePassStatus).isNotNull(InvoiceRecordDo::getInvoiceNumber)
                .gt(InvoiceRecordDo::getCreateTime, DateUtils.dateFormatToString(DateUtils.passingDate(new Date(), -180)))
                .ne(InvoiceRecordDo::getInvoiceNumber, ""));
        for (InvoiceRecordDo et : list) {
            this.matchInvoiceLink(et.getId());
        }
    }

    @Override
    public Object matchInvoice(RechargeRecordMatchInvoiceReq req, Long userId) {
        RechargeRecordDo rechargeRecordDo = rechargeRecordService.getBaseMapper().selectById(req.getRechargeRecordId());
        if (rechargeRecordDo == null) {
            throw new BizException(SysConstant.RechargeRecord_Data_NotExist);
        }

        InvoiceRecordDo invoiceRecordDo = dao.selectById(req.getInvoiceRecordId());
        if (invoiceRecordDo == null) {
            throw new BizException(SysConstant.InvoiceRecord_Data_NotExist);
        }
        if (invoiceRecordDo.getCompanyId().longValue() != rechargeRecordDo.getCompanyId().longValue())
            throw new BizException(SysConstant.InvoiceRecord_NotMatch_Company);
        rechargeRecordDo.setInvoiceRecordId(invoiceRecordDo.getId());
        rechargeRecordService.updateById(rechargeRecordDo);
        return null;
    }

    /**
     * 定时器 固定月开
     */
    @Override
    public void timingReview() {
        List<InvoiceReviewDto> list = dao.getInvoiceCompany();
        for (InvoiceReviewDto dto : list) {
            //判断本月是否开过
            if (jug(dto.getId())) {
                continue;
            }
//            if (!updateCheck(dto.getId(), dto.getAmount())) {
//                continue;
//            }
            InvoiceTitleDo titleDo = invoiceTitleDao.selectById(dto.getLastInvoiceTitleId());
            if (titleDo == null) {
                continue;
            }
            InvoiceRecordDo et = new InvoiceRecordDo();
            BeanUtils.copyProperties(titleDo, et);
            et.setStatus(DicBusinessItemConstant.invoiceApplyStatus);
            et.setType(0);
            et.setInvoiceAmount(dto.getAmount());
            et.setCompanyId(dto.getId());
            et.setTips("定时任务自动生成");
            et.setDeleteFlag(0);
            et.setCreateTime(new Date());
            dao.insert(et);
        }


    }

    public boolean jug(Long companyId) {
        QueryWrapper<InvoiceRecordDo> queryWrapper = new QueryWrapper<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String strDate = sdf.format(new Date());
        queryWrapper.eq("company_id", companyId).last(String.format(" and DATE_FORMAT(create_time,'%1$s') = '%2$s' limit 1", "%Y-%m", strDate));
        InvoiceRecordDo record = dao.selectOne(queryWrapper);
        if (record != null) {
            return true;
        }
        return false;
    }


    /**
     * 获取最近 60 天未审核的数量
     */
    @Override
    public int getUnCheckCount(Long companyId) {
        LambdaQueryWrapper<InvoiceRecordDo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InvoiceRecordDo::getStatus, DicBusinessItemConstant.invoiceApplyStatus);
        queryWrapper.ge(InvoiceRecordDo::getCreateTime, DateUtils.dateFormatToString(DateUtils.passingDate(new Date(), -60)));
        if (companyId != null) {
            queryWrapper.eq(InvoiceRecordDo::getCompanyId, companyId);
        }
        int count = dao.selectCount(queryWrapper);
        return count;
    }

    /**
     * 获取最近未匹配的开票记录数量
     */
    @Override
    public int getUnMatchInvoiceRecordCount(Long companyId, String taxNumber) {
        int count = dao.getUnMatchInvoiceRecord(companyId, taxNumber);
        return count;
    }


    @Override
    public Map<String, Integer> getFinanceUnCheckCount(Long company) {
        Map<String, Integer> map = new HashMap<>();
        map.put("invoiceCount", this.getUnCheckCount(company));
        map.put("rechargeCount", rechargeRecordService.getUnCheckCount(company));
        map.put("rechargeDetailCount", rechargeRecordService.getUnExamineCount(company));
        map.put("abnormal", messageNoticeService.getRackUnDealCount());//异常库位

        return map;
    }
}
